package git.soulbgm.utils;

import io.netty.buffer.ByteBuf;
import io.netty.util.internal.MathUtil;

import java.util.Arrays;

/**
 * netty包方法重写
 */
public class ByteBufferUtil {

    public static byte[] getBytes(ByteBuf buf) {
        return getBytes(buf, buf.readerIndex(), buf.readableBytes());
    }

    public static byte[] getBytes(ByteBuf buf, int start, int length) {
        return getBytes(buf, start, length, true);
    }

    public static byte[] getBytes(ByteBuf buf, int start, int length, boolean copy) {
        if (MathUtil.isOutOfBounds(start, length, buf.capacity())) {
            throw new IndexOutOfBoundsException("expected: 0 <= start(" + start + ") <= start + length(" + length + ") <= buf.capacity(" + buf.capacity() + ')');
        } else if (buf.hasArray()) {
            if (!copy && start == 0 && length == buf.capacity()) {
                return buf.array();
            } else {
                int baseOffset = buf.arrayOffset() + start;
                return Arrays.copyOfRange(buf.array(), baseOffset, baseOffset + length);
            }
        } else {
            byte[] v = new byte[length];
            buf.getBytes(start, v);
            return v;
        }
    }

}
